package com.itxx.allTools.KeyCase.test2;

import java.util.Scanner;

//二分查找
public class Test {
    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 8, 9, 11, 22, 33, 44, 55, 66};
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你要查找的数");
        int num = sc.nextInt();
        int sort = getindex(arr, num);
        if (sort == -1) {
            System.out.println("你查找的数不存在");
        }
        System.out.println("你查找的数:" + arr[sort] + "索引是:" + sort);
    }

    public static int getindex(int arr[], int number) {
        /*
         * 定义一个 min=0  max=数组长度-1
         * 进入循环,循环条件(min<=max)如果 min大于max 结束循环 查找的条数据不存在
         *算出中间索引middle= (min+max)/2
         * 是  返回 middle
         * 否    返回 -1
         * */
        int index = -1;
        int min = 0;
        int max = arr.length - 1;
        //判断要判断的数字在数组范围内
        if (number < arr[0] || number > arr[arr.length - 1]) {
            //不在  直接返回index
            return index;
        }
        while (min <= max) {
            //计算中间索引
            int middle = (min + max) / 2;

            /*if (arr[middle] == number) {
                //arr[middle]==number 返回middle
                return middle;
            } else */
            if (arr[middle] > number) {
                //middle>num 要查找的数在左边  范围变为  min  -   middle-1
                max = middle - 1;
            } else if (arr[middle] < number) {
                //middle<num  要查找的数在右边,范围变为 middle+1 -   max
                min = middle + 1;
            } else if (arr[middle] == number) {
                //arr[middle]==number 返回middle
                return middle;
            }
        }
        //while结束后
        return index;
    }
}